import os
import cv2
from pathlib import Path
import json
import subprocess


import os
from pathlib import Path
from typing import Optional
import os
from pathlib import Path

import cv2


def get_video_frame_count(video_path):
    try:
        # 打开视频文件
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            print("无法打开视频文件")
            return 0
        # 获取视频的总帧数
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        # 释放视频捕获对象
        cap.release()
        return frame_count
    except Exception as e:
        print(f"发生错误: {e}")
        return 0



def create_nested_folders(folder1: str, folder2: str, event = "problem_cross") -> str:
    """
    根据输入的两个字符串创建嵌套文件夹
    
    参数:
        folder1: 第一级文件夹名称 (在当前路径下创建)
        folder2: 第二级文件夹名称 (在第一级文件夹下创建)
    
    返回:
        最终创建的完整路径字符串
    
    异常:
        可能抛出 OSError 如果创建文件夹失败
    """
    # 使用 pathlib 处理路径更安全
    current_dir = Path.cwd()
    first_level = current_dir / folder1
    second_level = first_level / folder2
    third_level = second_level / event
    try:
        # 创建第一级文件夹 (exist_ok=True 表示如果已存在则不会报错)
        first_level.mkdir(exist_ok=True)
        second_level.mkdir(exist_ok=True)
        third_level.mkdir(exist_ok=True)

        # print(f"已创建第三级文件夹:{first_level} {second_level}  {third_level}")

        return str(third_level)
    
    except OSError as e:
        print(f"创建文件夹失败: {e}")
        raise


def reset_video_processed_status(video_queue: dict, camera_name: str, video_name: str) -> bool:
    """
    重置指定视频处理状态并更新队列状态

    参数:
    video_queue (dict): 视频队列数据结构
    camera_name (str): 摄像头目录名称（大小写敏感）
    video_name (str): 视频文件名（可带或不带.mp4扩展）

    返回:
    bool: True表示成功修改，False表示无需修改

    异常:
    ValueError: 当摄像头或视频不存在时抛出
    """
    # 标准化视频文件名
    video_name = video_name.strip()
    if not video_name.lower().endswith('.mp4'):
        video_name += '.mp4'

    # 遍历视频队列
    target_queue = None
    queue_path = None  # 新增变量存储队列路径
    for path, info in video_queue.items():
        if path == camera_name:  # 直接匹配完整的队列路径
            target_queue = info
            queue_path = path    # 存储完整的队列路径
            break

    if not target_queue:
        raise ValueError(f"Cannot find camera: {camera_name}")

    # 查找目标视频
    video_found = False
    status_changed = False
    for video in target_queue['videos']:
        if video['video'].lower() == video_name.lower():
            video_found = True
            if video['processed']:
                video['processed'] = False
                status_changed = True
            break

    if not video_found:
        raise ValueError(f"Video '{video_name}' not found in camera '{camera_name}'")

    # 如果状态有变化，更新队列状态
    if status_changed:
        # 更新队列完成状态
        all_processed = all(v['processed'] for v in target_queue['videos'])
        target_queue['queue_processed'] = all_processed

        # 新增优先级调整逻辑
        if target_queue['priority'] == -1:
            # 只有当队列原优先级为-1时才调整
            update_queue_priority(video_queue, queue_path)  # 使用完整的队列路径
            
        # 强制修正队列完成状态
        if not all_processed and target_queue['queue_processed']:
            target_queue['queue_processed'] = False

    return status_changed


def get_latest_image(folder_path: str, check_subdir: bool = False) -> Optional[str]:
    """
    获取指定文件夹下最新创建的图片文件路径
    
    参数：
    folder_path (str): 要搜索的文件夹路径
    check_subdir (bool): 是否检查子目录，默认False
    
    返回：
    str | None: 最新图片的完整路径，如果没有找到返回None
    
    异常：
    ValueError: 当输入路径不存在或不是目录时
    """
    # 验证输入路径
    target_dir = Path(folder_path)
    if not target_dir.exists():
        raise ValueError(f"路径不存在: {folder_path}")
    if not target_dir.is_dir():
        raise ValueError(f"路径不是目录: {folder_path}")

    # 支持的图片扩展名（可扩展）
    image_exts = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'}
    
    # 递归遍历模式选择
    if check_subdir:
        walk_method = target_dir.rglob('*')  # 包含子目录
    else:
        walk_method = target_dir.glob('*')    # 仅当前目录

    latest_image = None
    max_time = 0
    
    for entry in walk_method:
        try:
            # 跳过目录和非文件项
            if not entry.is_file():
                continue
                
            # 检查扩展名
            if entry.suffix.lower() not in image_exts:
                continue
            
            # 跳过隐藏文件（Unix-like系统）
            if entry.name.startswith('.'):
                continue
            
            # 获取文件状态（优化性能，只获取必要信息）
            stat = entry.stat()
            
            # 使用最后修改时间作为判断标准
            mod_time = stat.st_mtime
            
            # 更新最新文件
            if mod_time > max_time:
                max_time = mod_time
                latest_image = str(entry.resolve())
                
        except PermissionError:
            # 跳过无权限访问的文件
            continue
        except Exception as e:
            # 记录意外错误但继续执行
            print(f"处理文件 {entry} 时出错: {str(e)}")
            continue

    return latest_image if latest_image else None


def getdiskinfo():
    try:
        # 运行 sudo fdisk -l 命令
        result = subprocess.run(['sudo', 'fdisk', '-l'], capture_output=True, text=True, check=True)
        output = result.stdout
        # 查找 U 盘信息，通常 U 盘设备名以 /dev/sd 开头
        print("get info of disk")
        usb_info = []
        lines = output.splitlines()
        for i, line in enumerate(lines):
            if line.startswith('/dev/sd'):
                # 这里可以根据实际情况进一步解析 U 盘信息
                usb_info.append(line)
        if usb_info:
            print("检测到的 U 盘信息:")
            print(usb_info)
        return usb_info
    except subprocess.CalledProcessError as e:
        print(f"执行命令时出错: {e.stderr}")
        return []
    except Exception as e:
        print(f"发生未知错误: {e}")
        return []

def _is_mounted( device):
    with open('/proc/mounts', 'r') as f:
        return any(line.startswith(device) for line in f)

def mount_usb():
    try:
        # 获取U盘信息
        print("-++++-")
        usb_info = getdiskinfo()
        print("----")
        if not usb_info: 
            return {"status": "error", "message": "未检测到可用的U盘设备"}

        # 提取第一个U盘设备（可根据实际需求调整）
        raw_line = usb_info[0]
        device_path = raw_line.split()[0]  # 提取/dev/sda1
        
        # 检查是否已挂载
        # if ._is_mounted(device_path):
        #     return {"status": "success", "message": "设备已挂载", "mount_point": "/mnt/usb"}

        # 创建挂载目录（带权限检查）
        mount_point = "/mnt/usb"
        # self._safe_create_dir(mount_point)

        # 执行挂载命令（自动检测文件系统）
        mount_cmd = f"sudo mount {device_path} {mount_point}"
        result = subprocess.run(
            mount_cmd.split(),
            capture_output=True,
            text=True,
            timeout=10
        )

        # 处理挂载结果
        if result.returncode == 0:
            # 验证挂载状态
            # if self._is_mounted(device_path):
            #     return {
            #         "status": "success",
            #         "device": device_path,
            #         "mount_point": mount_point,
            #         "capacity": self._get_disk_size(device_path)
            #     }
            return {"status": "warning", "message": "挂载验证失败"}
        
        # 处理已知错误
        error_msg = result.stderr.lower()
        if "wrong fs type" in error_msg:
            return self._mount_with_type(device_path, mount_point)
        elif "already mounted" in error_msg:
            return {"status": "success", "message": "设备已挂载"}
        
        return {"status": "error", "message": f"挂: {error_msg}"}

    except Exception as e:
        return {"status": "error", "message": f"操作异常: {str(e)}"}

def get_parent_dir(file_path):
    """从文件路径中提取直接父目录名称"""
    normalized_path = os.path.normpath(file_path)  # 规范化路径
    dir_path = os.path.dirname(normalized_path)    # 获取文件所在目录路径
    return os.path.basename(dir_path)              # 提取目录名称


def get_folders_in_disk(directory):
    folder_list = []
    # 遍历指定目录下的所有文件和文件夹
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        # 判断是否为文件夹
        if os.path.isdir(item_path):
            folder_list.append(item_path)
    return folder_list


def get_mp4_paths(directory):
    path = Path(directory)
    mp4_paths = [str(item.absolute()) for item in path.rglob('*.mp4')]
    return mp4_paths


def get_video_info(video_path, image_format='jpg'):
    """
    获取视频信息并保存首帧画面
    
    参数：
    video_path -- 视频文件路径
    image_format -- 保存的图片格式（默认jpg）
    
    返回：
    (fps, width, height, total_frames, duration, cover_path) 
    包含帧率、宽高、总帧数、时长(秒)、封面路径的元组
    """
    # 初始化返回值
    cover_path = None
    total_frames = 0
    duration = 0.0
    
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"无法打开视频文件：{video_path}")
    
    try:
        # 获取基础信息
        fps = cap.get(cv2.CAP_PROP_FPS)
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        
        # 获取总帧数
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        
        # 计算视频时长（处理fps为0的异常情况）
        if fps > 0:
            duration = round(total_frames / fps, 2)
        else:
            # 如果无法通过帧数计算时长，尝试直接获取
            duration = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000
            
        # 读取首帧
        success, frame = cap.read()
        if not success:
            raise RuntimeError("无法读取视频首帧，可能为空文件")
            
        # 生成封面路径
        dir_name = os.path.dirname(video_path)
        base_name = os.path.splitext(os.path.basename(video_path))[0]
        cover_path = os.path.join(dir_name, f"{base_name}.{image_format}")
        
        # 保存封面（自动创建目录）
        os.makedirs(dir_name, exist_ok=True)
        if not cv2.imwrite(cover_path, frame):
            raise IOError(f"封面保存失败：{cover_path}")
            
        return fps, width, height,  duration, cover_path
        
    finally:
        cap.release()


def update_queue_priority(video_queue, queue_path):
    """
    将指定队列的优先级设置为当前最大优先级+1
    
    参数：
    video_queue -- 视频队列数据结构
    queue_path -- 要修改的摄像头路径
    
    返回：
    新的优先级数值
    """
    # 参数校验
    if queue_path not in video_queue:
        raise ValueError(f"指定的队列路径不存在: {queue_path}")

    # 获取当前最大优先级
    max_priority = -1
    for q in video_queue.values():
        if q['priority'] > max_priority:
            max_priority = q['priority']

    # 设置新优先级
    new_priority = max_priority + 1
    video_queue[queue_path]['priority'] = new_priority
    return new_priority

def adjust_priority_and_pause(video_queue: dict, camera_name: str, video_name: str) -> None:
    """
    调整队列优先级并设置视频暂停状态
    
    参数:
    video_queue (dict): 视频队列数据结构
    camera_name (str): 目标摄像头名称（目录名）
    video_name (str): 需要保持运行的目标视频文件名（带扩展名）

    功能:
    1. 将所有现有优先级 >=0 的队列优先级 +1
    2. 将指定摄像头队列优先级设为0
    3. 将该队列下除指定视频外的其他视频设为暂停状态

    异常:
    ValueError: 当摄像头或视频不存在时抛出
    """
    # 参数预处理
    video_name = os.path.basename(video_name)  # 标准化输入
    print("video_name: ",video_name)
    print("camera_name:--",camera_name)
    # 第一步：所有现有队列优先级+1（排除未设置的-1）
    for queue_info in video_queue.values():
        if queue_info.get('priority', -1) >= 0:
            queue_info['priority'] += 1

    # 第二步：查找目标摄像头队列
    target_queue = None
    # print("video_queue:",video_queue)
    for queue_path, q_info in video_queue.items():
        # print("os.path.basename(queue_path):",os.path.basename(queue_path))
        if queue_path == camera_name:
            target_queue = q_info
            break
    
    if not target_queue:
        raise ValueError(f"未找到指定摄像头------: {camera_name}")

    # 设置目标队列优先级为0
    target_queue['priority'] = 0

    # 第三步：处理视频暂停状态
    video_found = False
    for video in target_queue['videos']:
        # 匹配目标视频
        if os.path.basename(video['video']) == video_name:
            video['paused'] = False  # 确保目标视频运行
            video_found = True
        else:
            video['paused'] = True  # 暂停其他视频

    if not video_found:
        raise ValueError(f"在摄像头 {camera_name} 中未找到视频: {video_name}")

    # 更新队列级暂停状态（如果整个队列都暂停则设置）
    target_queue['queue_paused'] = all(v['paused'] for v in target_queue['videos'])


def modify_queue_info(video_queue, queue_path, **kwargs):
    """
    修改队列信息，如果设置队列为运行状态且优先级为-1，则自动设置优先级
    
    参数：
    video_queue -- 视频队列数据结构
    queue_path -- 要修改的摄像头路径
    kwargs -- 需要更新的字段键值对
    
    新增逻辑：
    - 当设置queue_processed=False(开始运行)时：
      1. 如果当前优先级为-1，则设置为最大优先级+1
      2. 否则保持原优先级
    """
    print("queue_path: ",queue_path)
    # 参数校验
    if queue_path not in video_queue:
        raise ValueError(f"指定的队列路径不存在: {queue_path}")

    
    # 检查是否需要处理优先级
    if 'queue_paused' in kwargs and kwargs['queue_paused'] is False:
        current_priority = video_queue[queue_path].get('priority', -1)
        print("current_priority: ",current_priority)
        # 优先级为-1时需要自动设置
        if current_priority == -1:
            # 获取当前最大优先级
            max_priority = -1
            for q in video_queue.values():
                if q['priority'] > max_priority:
                    max_priority = q['priority']
            
            # 设置新优先级
            new_priority = max_priority + 1
            video_queue[queue_path]['priority'] = new_priority
            print(f"自动设置优先级: {queue_path} -> {new_priority}")

    # 处理其他字段修改
    type_checks = {
        'queue_processed': bool,
        'queue_paused': bool,
        'priority': int
    }

    for key, value in kwargs.items():
        # 类型检查
        expected_type = type_checks.get(key)
        if expected_type and not isinstance(value, expected_type):
            raise TypeError(f"字段 {key} 需要 {expected_type} 类型")

        # 更新字段值（优先级已单独处理，跳过）
        if key != 'priority':
            video_queue[queue_path][key] = value

    return True



def extract_parent_directory(file_path):
  
    # 标准化路径（处理多余的斜杠和相对路径）
    normalized_path = os.path.normpath(file_path)
    
    # 获取父目录路径
    parent_dir = os.path.dirname(normalized_path)
    
    # 处理根目录的特殊情况
    if parent_dir == os.path.dirname(parent_dir):
        return parent_dir
    
    return parent_dir

def mark_video_processed(video_queue: dict, camera_path: str, video_path: str) -> bool:
    print("mark_video_processed: -------------- ",mark_video_processed)
    """
    标记指定摄像头下的特定视频为已处理
    
    参数:
        video_queue: 视频队列数据结构
        camera_path: 摄像头路径（必须与队列中的key完全匹配）
        video_path: 视频文件完整路径
    
    返回:
        bool: 是否成功修改
    
    异常:
        ValueError: 当摄像头或视频不存在时
    """
    # 检查摄像头是否存在
    if camera_path not in video_queue:
        raise ValueError(f"摄像头路径不存在: {camera_path}")
    
    # 在摄像头队列中查找视频
    target_video = None
    for video in video_queue[camera_path]['videos']:
        if video['video_path'] == video_path:
            target_video = video
            break
    
    # 检查是否找到视频
    if not target_video:
        raise ValueError(f"视频路径不存在于该摄像头: {video_path}")
    
    # 修改状态
    target_video['processed'] = True
    
    # 更新摄像头队列状态
    video_queue[camera_path]['queue_processed'] = all(
        v['processed'] for v in video_queue[camera_path]['videos']
    )
    
    return True


# def modify_video_pause_state(video_queue, camera_name, video_name, paused):
#     """
#     修改指定视频的暂停状态
#     :param video_queue: 视频队列数据结构
#     :param camera_name: 摄像头名称（对应队列key的basename）
#     :param video_name: 视频文件名（带.mp4后缀）
#     :param paused: 要设置的暂停状态（True/False）
#     :return: 修改成功返回True，否则False
#     """
#     # 标准化输入参数
#     video_name = os.path.basename(video_name)
#     if not video_name.endswith('.mp4'):
#         video_name += '.mp4'

#     # 遍历队列查找匹配项
#     for queue_path, queue_info in video_queue.items():
#         # 匹配摄像头名称
#        .path.basename(queue_path) == camera_name:
#             # 在视频列表中查找
#             for video in queue_info['videos']:
#                 if os.path.basename(video['video_path']) == video_name:
#                     # 类型检查
#                     if not isinstance(paused, bool):
#                         raise TypeError("paused参数必须为布尔值")
#                     # 更新状态
#                     video['paused'] = paused
#                     return True
#     return False

#根据摄头参数找到对应摄像头找到对应视频
def find_videopath_by_camera_movie(camera: str, video: str, video_queue: dict) -> str:
    """
    根据摄像头名称和视频名称查找对应的视频路径
    
    参数:
        camera (str): 摄像头名称（对应目录名称，大小写敏感）
        video (str): 视频文件名（需包含扩展名，如 'video1.mp4'）
        video_queue (dict): build_video_queue 返回的视频队列结构
    
    返回:
        str: 匹配的视频完整路径
    
    异常:
        ValueError: 未找到匹配项时抛出
    """
    # 遍历所有摄像头队列
    for queue_path, queue_info in video_queue.items():
        # 提取当前队列的摄像头名称（目录名）
        current_camera = os.path.basename(queue_path)
        
        # 摄像头名称匹配
        if current_camera == camera:
            # 遍历该摄像头下的所有视频
            for video_info in queue_info['videos']:
                # 视频文件名匹配（精确匹配）
                if video_info['video'] == video:
                    return video_info['video_path']
    
    # 未找到匹配项时抛出异常
    raise ValueError(f"未找到摄像头 '{camera}' 下的视频文件 '{video}'")


def build_video_queue(root_directory, reread =False):
    """
    构建二级队列数据结构
    1. 先检查是否存在 video_queue_info.json
    2. 存在则读取已有队列，不存在则创建新队列
    """
    queue_file = os.path.join(root_directory, "video_queue_info.json")
    
    # 尝试读取现有队列
    if not reread:
        existing_queue = read_video_queue_from_json(queue_file)
        if existing_queue is not None:
            print(f"使用现有队列文件: {queue_file}")
            return existing_queue

    # 不存在则创建新队列
    print(f"未找到队列文件，开始构建新队列...")
    video_queue = {}
    for folder in get_folders_in_disk(root_directory):
        mp4_list = get_mp4_paths(folder)
        print("扫描到MP4文件:", mp4_list)
        
        video_list = []
        for mp4 in mp4_list:
            # 获取视频元数据
            try:
                fps, width, height, duration, cover_path = get_video_info(mp4)
            except Exception as e:
                print(f"跳过无效视频文件 {mp4}: {str(e)}")
                continue
            video_name = os.path.basename(mp4)
            # 构建视频信息结构
            video_info = {
                'camera': os.path.basename(folder),
                'video': video_name,  
                'video_path': mp4,
                'processed': False,
                'paused': False,  # 新增暂停状态字段
                'fps': fps,
                'width': width,
                'height': height,
                'video_duration': duration,
                'cover_path': cover_path,
                'sidewalk_coordinates': [(0, 0), (0, 0), (0, 0), (0, 0)],
                'traffic_light_coordinates': [(0, 0), (0, 0)],
                'alarm_data_path': ""
            }
            video_list.append(video_info)

        # 构建摄像头队列
        queue_info = {
            'videos': video_list,
            'queue_processed': False,
            'queue_paused': False,
            'priority': -1
        }
        video_queue[folder] = queue_info

    # 写入新队列文件
    try:
        with open(queue_file, 'w', encoding='utf-8') as f:
            json.dump(video_queue, f, ensure_ascii=False, indent=4)
        print(f"新队列已保存至: {queue_file}")
    except Exception as e:
        print(f"队列文件保存失败: {str(e)}")

    return video_queue


def read_video_queue_from_json(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
    except json.JSONDecodeError:
        print(f"解析 {file_path} 时出现 JSON 解码错误。")
    except Exception as e:
        print(f"读取文件 {file_path} 时出现未知错误: {e}")
    return None


def extract_videos_by_priority(json_file_path):
    loaded_video_queue = read_video_queue_from_json(json_file_path)
    if not loaded_video_queue:
        return []

    new_queue = []
    # 按照优先级排序，优先级高的在前
    sorted_queues = sorted(loaded_video_queue.items(), key=lambda x: x[1]['priority'])

    for _, queue_info in sorted_queues:
        priority = queue_info['priority']
        queue_processed = queue_info['queue_processed']

        if priority == -1 or queue_processed:
            continue

        for video in queue_info['videos']:
            if (
                not video['processed'] 
                and not video.get('paused', False)  # 新增条件
                and not queue_info.get('queue_paused', False)
            ):
                new_queue.append(video)

    return new_queue

def extract_videos_direct(video_queue_struct):
    """
    直接从内存中的视频队列结构体提取待处理视频
    
    参数：
    video_queue_struct -- build_video_queue返回的原始结构体
    
    返回：
    按优先级排序的视频列表，格式与extract_videos_by_priority一致
    """
    if not isinstance(video_queue_struct, dict):
        raise TypeError("输入必须为build_video_queue生成的结构体")

    new_queue = []
    
    # 按优先级排序队列（优先级高的在前）
    sorted_queues = sorted(
        video_queue_struct.items(),
        key=lambda x: x[1].get('priority', -1)
    )

    for queue_path, queue_info in sorted_queues:
        # 跳过已处理或未设置优先级的队列
        if queue_info.get('priority', -1) == -1 or queue_info.get('queue_processed', False):
            continue

        # 收集未处理的视频
        for video in queue_info.get('videos', []):
            # 新增状态检查条件
            if (
                not video.get('processed', True) 
                and not video.get('paused', False)  # 检查暂停状态
                and not queue_info.get('queue_paused', False)  # 检查队列级暂停
            ):
                new_queue.append(video.copy())

    return new_queue

def extract_videos_anyway(video_queue_struct):
    """
    直接从内存中的视频队列结构体提取待处理视频
    
    参数：
    video_queue_struct -- build_video_queue返回的原始结构体
    
    返回：
    按优先级排序的视频列表，格式与extract_videos_by_priority一致
    """
    if not isinstance(video_queue_struct, dict):
        raise TypeError("输入必须为build_video_queue生成的结构体")

    new_queue = []
    
    # 按优先级排序队列（优先级高的在前）
    sorted_queues = sorted(
        video_queue_struct.items(),
        key=lambda x: x[1].get('priority', -1)
    )

    for queue_path, queue_info in sorted_queues:
        # 跳过已处理或未设置优先级的队列
        for video in queue_info.get('videos', []):

            new_queue.append(video.copy())

    return new_queue

# # 指定目录路径
# directory_path = '/home/chenwei/cw/nn'
# folders = build_video_queue(directory_path)


# # 将 video_queue 信息写入 JSON 文件

# output_file = '/data/control_communication/video_queue_info.json'

# new_queue = extract_videos_by_priority(output_file)


# print("新队列中的视频数据：")
# for video in new_queue:
#     print(f"  视频路径: {video['video_path']}")
#     print(f"  是否处理完毕: {video['processed']}")
#     print(f"  帧率: {video['fps']}")
#     print(f"  视频每帧宽度: {video['width']}")
#     print(f"  视频每帧高度: {video['height']}")
#     print(f"  人行道区域四个点坐标: {video['sidewalk_coordinates']}")
#     print(f"  红绿灯左上角和右下角坐标: {video['traffic_light_coordinates']}")
#     print(f"  报警数据存放路径: {video['alarm_data_path']}")
#     print()


# try:
#     with open(output_file, 'w', encoding='utf-8') as f:
#         json.dump(folders, f, ensure_ascii=False, indent=4)
#     print(f"已将 folders 信息写入 {output_file}")
# except Exception as e:
#     print(f"写入 JSON 文件时出错: {e}")

# # 读取 JSON 文件
# loaded_video_queue = read_video_queue_from_json(output_file)
# if loaded_video_queue:
#     print("成功从 JSON 文件中读取 video_queue 信息：")
#     for camera, queue_info in loaded_video_queue.items():
#         print(f"摄像头: {camera}")
#         print(f"  队列是否处理完毕: {queue_info['queue_processed']}")
#         print(f"  队列是否暂停: {queue_info['queue_paused']}")
#         print(f"  队列优先级: {queue_info['priority']}")
#         for video in queue_info['videos']:
#             print(f"    视频路径: {video['video_path']}")
#             print(f"    是否处理完毕: {video['processed']}")
#             print(f"    帧率: {video['fps']}")
#             print(f"    视频每帧宽度: {video['width']}")
#             print(f"    视频每帧高度: {video['height']}")
#             print(f"    人行道区域四个点坐标: {video['sidewalk_coordinates']}")
#             print(f"    红绿灯左上角和右下角坐标: {video['traffic_light_coordinates']}")
#             print(f"    报警数据存放路径: {video['alarm_data_path']}")
#             print()


